package chat.aylan.top.communicate;
/**
 * 消息接受器
 */

import chat.aylan.top.commons.User;
import chat.aylan.top.database.service.UserServicce;
import chat.aylan.top.wind.ManagerWind;
import com.alibaba.fastjson.JSONObject;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

public class ReceiverThread implements Runnable {

    private DataInputStream dis;
    private boolean isRunning;

    private ManagerWind managerWind;

    public ReceiverThread(Socket socket,ManagerWind managerWind){
        isRunning = true;
        this.managerWind = managerWind;
        try {
            dis = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readMsg(){
        try {
          String msg =  dis.readUTF();
          System.out.println("customer "+msg);
          JSONObject json = JSONObject.parseObject(msg);
          if(json.getInteger("type") == 2){
              managerWind.someOneSay(json.getJSONObject("user"),json.getString("message"));
          }else if(json.getInteger("type") == 1){
              //  某人上线
              User user = json.getObject("user", User.class);
              managerWind.updateFriends(user,(short) 1);
          }else if(json.getInteger("type") == 3){
              // 某人下线
              User user = json.getObject("data", User.class);
              managerWind.updateFriends(user,(short) 0);
          }else if(json.getInteger("type") == 4){
              //  上线成功
              UserServicce servicce;
              try{
                  servicce = new UserServicce();
                  managerWind.user.setStatus((short) 1);
                  servicce.updateUser(managerWind.user);
                  managerWind.setList();
              }catch (Exception e){
                    e.printStackTrace();
              }
          }else if(json.getInteger("type") == 5){
              //   群聊
              managerWind.updateGroup(json);
          }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void run() {
        while (isRunning){
            readMsg();
        }
    }
}
